﻿using QWManage.Model;
using QWManage.Utils;
using System;
using System.Text.RegularExpressions;

namespace QWManage.API.AccessToken
{
    public class TokenB
    {
        public static string GetAccessToken(bool force = false)
        {
            string token = string.Empty;
            if (!force) token = Common.GetCachedToken(false);

            if (!string.IsNullOrEmpty(token)) return token;
            AppConfigInfo appConfig = AppCofingMgr.Get();
            string url = $"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={appConfig.Corpid}&corpsecret={appConfig.CorpsecretB}";

            string html = HttpHelper.GetHtmlSource(url);
            string pattern = "\"access_token\":\"(?<token>.*?)\"";
            token = Regex.Match(html, pattern).Groups["token"].Value.Trim();
            if (string.IsNullOrEmpty(token))
                throw new Exception("未能正确获取到Token:" + html);
            Common.CacheToken(token, false);
            return token;
        }
    }
}
